<template>
  <div class="main" style="height: 100vh; display: flex; align-items: center; justify-content: center; background-color: rgb(34, 141, 64)">
    <div style="display: flex; background-color:#F0F0F0;opacity:0.8; width: 50%;height:70%; border-radius: 5px; overflow: hidden">
      <div style="flex: 1">
        <img src="@/assets/register.png" alt="" style="width: 100%;margin-top: 80px">
      </div>
      <div style="flex: 1; display: flex; align-items: center; justify-content: center">
        <el-form :model="user" style="width: 80%" :rules="rules" ref="registerRef">
          <div style="font-size: 20px; font-weight: bold; text-align: center; margin-bottom: 20px">
            欢迎注册挂号看诊系统
          </div>
          <el-form-item prop="email">
            <el-input prefix-icon="el-icon-message" size="medium" placeholder="请输入邮箱" v-model="user.email"
                      clearable status-icon></el-input>
          </el-form-item>
          <el-form-item prop="verificationCode">
            <el-input prefix-icon="el-icon-chat-dot-square" size="medium" placeholder="请输入动态码"
                      style="width: 150px" v-model="user.verificationCode" clearable></el-input>
            <el-button type="info" style="height:35px;margin-left: 10px" :disabled="disabled" @click="getCode">
              {{ content }}
            </el-button>
          </el-form-item>
          <el-form-item prop="phonenumber">
            <el-input prefix-icon="el-icon-mobile" size="medium" placeholder="请输入手机号码" v-model="user.phonenumber"
                      clearable></el-input>
          </el-form-item>
          <el-form-item prop="userName">
            <el-input prefix-icon="el-icon-user" size="medium" placeholder="请输入用户名" v-model="user.userName"
                      clearable></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input prefix-icon="el-icon-lock" size="medium" show-password placeholder="请输入密码"
                      v-model="user.password" clearable></el-input>
          </el-form-item>
          <el-form-item prop="confirmPass">
            <el-input prefix-icon="el-icon-lock" size="medium" show-password placeholder="请确认密码"
                      v-model="user.confirmPass" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="info" style="width: 100%" @click="register">注 册</el-button>
          </el-form-item>
          <div style="display: flex">
            <div style="flex: 1">已经有账号了？请 <span style="color: #6e77f2; cursor: pointer" @click="$router.push('/login')">登录</span></div>
          </div>
        </el-form>
      </div>
    </div>

  </div>
</template>

<script>

import {isEmailExist, isPhonenumberExist, isUsernameExist, register, sendEmailCode, verifyEmailCode} from "@/api/user";

export default {
  name: "Register",
  data() {
    // 验证码校验
    const validatePassword = (rule, confirmPass, callback) => {
      if (confirmPass === null) {
        callback(new Error('请确认密码'))
      } else if (confirmPass !== this.user.password) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    };
    const validateEmail = (rule, email, callback) => {
      const reg = /^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/;
      if (email == null) {
        this.pass = false;
        callback(new Error('请输入邮箱地址'))
      } else if (!reg.test(email)) {
        this.pass = false;
        callback(new Error('请输入正确的邮箱地址'))
      } else {
        let params={
            email: this.user.email,
          }
        isEmailExist(params).then(res => {
          if(res.code!=200){
            callback(new Error(res.msg))
          }else{
            callback();
          }
      })
      }
    };

    const validateCode = (rule, code, callback) => {
      if (code == null) {
        callback(new Error('请输入动态码'))
      }else if(code.length!=6){
        callback(new Error('动态码为6位'))
      }else{
        let params={
            email: this.user.email,
            dynamicCode:code
          }
        verifyEmailCode(params).then(res => {
          if(res.code!=200){
            callback(new Error('动态码错误或过期，请重新获取'))
          }else{
            callback();
          }
        })
      }
    };

    const validatePhonenumber=(rule,phonenumber, callback) => {
      if (phonenumber == null) {
        callback(new Error('请输入手机号码'))
      }else if(phonenumber.length!=11){
        callback(new Error('手机号码为11位'))
      }else{
          let params={
            phonenumber:this.user.phonenumber
          }
        isPhonenumberExist(params).then(res => {
          if(res.code!=200){
            callback(new Error('手机号码已被注册，请使用其他手机号码'))
          }else{
            callback();
          }
        })
      }
    };

    const validateUserName=(rule,userName, callback) => {
      if (userName == null) {
        callback(new Error('请输入用户名'))
      }else{
         let params={
           username:this.user.userName
          }
        isUsernameExist(params).then(res => {
          if(res.code!=200){
            callback(new Error('该用户已被注册'))
          }else{
            callback();
          }
        })
      }
    };


    return {
      user: {},
      email: null,
      disabled: false,
      second: null,
      timer: null,
      rules: {
        email: [
          {validator: validateEmail, trigger: 'blur'},
        ],
        verificationCode: [
          {validator: validateCode, trigger: 'blur'},
        ],
        phonenumber:[
            {validator: validatePhonenumber, trigger: 'blur'},
        ],
        userName: [
          {validator: validateUserName, trigger: 'blur'},
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 6, max: 25, message: '密码至少6位', trigger: 'blur'}
        ],
        confirmPass: [
          {validator: validatePassword, trigger: 'blur'}
        ],
      }
    }
  },
  created() {

  },
  methods: {
    register() {
      this.$refs['registerRef'].validate((valid) => {
        if (valid) {
          // 验证通过
         register(this.user).then(res => {
            if (res.code === 200) {
              this.$router.push('/login')
              this.$notify({
                title: '注册成功',
                message: '登录后请及时更新个人信息',
                type: 'warning'})
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    },
    countTime() {
      const TIME_COUNT = 60;
      if (!this.timer) {
        this.second = TIME_COUNT;
        this.disabled = true;
        this.timer = setInterval(() => {
          if (this.second > 0 && this.second <= TIME_COUNT) {
            this.second--;
          } else {
            this.disabled = false;
            clearInterval(this.timer);
            this.timer = null;
          }
        }, 1000);
      }
    },
    getCode() {
      if (this.pass) {
        this.countTime();
        let params={
            email: this.user.email
          }
        sendEmailCode(params).then(res => {
         if(res.code===200){
           this.$message({
             message:'动态码已发送到您的邮箱，请及时查看',
             type:'success',
             center:true
           });
         }else{
           this.$message({
             message:'动态码发送失败，请重新获取',
             type:'success',
             center:true
           });
         }
        })
      }
    }
  },
  computed: {
    content() {
      return this.disabled ? `${this.second}s后重新获取` : '获取动态码';
    },
    pass() {
      const reg = /^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/;
      return this.user.email != '' && reg.test(this.user.email) ? true : false;
    }
  }
}
</script>

<style scoped>
.main{
  background-image: url("../../public/bg4.jpg");
}
.code-btn {
  text-align: center;
  width: 100px;
  height: 34px;
  position: absolute;
  top: 1px;
  z-index: 222;
  color: #ef8466;
  font-size: 14px;
  border: 1px solid #bababa;
  border-radius: 5px;
  background-color: #fff;
  cursor: pointer;
}
</style>
